package encaps.entities;

import java.util.HashSet;
import java.util.Set;

public class Role {

    public static final String USER = "user";
    public static final String ADMIN = "admin";
    public static final String GUEST = "guest";
    public static final String MODERATOR = "moderator";
    public static final String TABLE_NAME = "role";
    private String roleName;
    private Set<Grant> grants = new HashSet<Grant>();

    public Role(String roleName) {
        this.roleName = roleName;
    }

    public Role(String roleName, Grant... grants) {
        this.roleName = roleName;
        for (Grant g : grants) {
            this.grants.add(g);
        }
    }

    public void setRoleName(String value) {
        roleName = value;
    }

    public void addGrant(Grant grant) {
        grants.add(grant);
    }

    public void removeGrant(Grant grant) {
        grants.remove(grant);
    }

    public String getRoleName() {
        return roleName;
    }

    public boolean hasGrant(Grant grant) {
        return grants.contains(grant);
    }

    public boolean hasGrant(String grantName) {
        return grants.contains(new Grant(grantName));
    }

    public String getGrantsAsString() {
        StringBuilder sb = new StringBuilder();
        for (Grant grant : grants) {
            sb.append(grant.getGrantName());
            sb.append(";");
        }
        return sb.toString();
    }

    public Set<Grant> getGrants() {
        return grants;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getName());
        sb.append(" = [roleName=");
        sb.append(roleName);
        sb.append(", grants: ");
        for (Grant grant : grants) {
            sb.append(grant.getGrantName());
            sb.append("; ");
        }
        sb.append("]");
        return sb.toString();
    }
}
